import Taro, { showToast } from "@tarojs/taro";
const interceptor = function (chain) {
  const requestParams = chain.requestParams;
  const { method, data, url } = requestParams;

  return chain.proceed(requestParams).then((res) => {
    console.log(`http <-- ${url} result:`, res);

    if (res.statusCode == 200) {
      switch (res.data.code) {
         case 1:
            return Promise.resolve(res.data);
         case 0:
            showToast({
               title: res.data.msg || 'success',
               icon: "none",
            });
            break;
         default:
            break;
      }
   }
   return Promise.reject(res.data);
    
   //  return res;
  });
};
Taro.addInterceptor(interceptor);


const request = async (
  url,
  method = "get",
  data,
  contentType = "application/json"
) => {
  return Taro.request({
    url: `${BASEAPI}${url}`,
    header: {
      authorization: "Bearer " + Taro.getStorageSync("userInfo").token,
      "content-type": contentType,
    },
    timeout: 10 * 1000,
    method,
    data
  });

  // try {
  //      let result = await Taro.request({
  //          url: `${BASEAPI}${url}`,
  //          header:{
  //             "authorization":"Bearer " + Taro.getStorageSync("userInfo").token,
  //             "content-type": contentType
  //          },
  //          timeout:10*1000,
  //          method,
  //          data
  //      })
  //      if (result.data.code == 0) {
  //       return result.data
  //      }else{
  //       showToast({
  //          title:result.data.msg,
  //          icon:"none"
  //        })
  //      }

  // } catch (error) {
  //      console.log(error);
  //      return '接口错误，请检查'
  // }
};

export default request;
